package net.mobgame.android;

import net.mobgame.common.Utils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {
	//	TopBarHeight topbar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_view);
		checkInternet();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	// check Internet
	public void checkInternet() {
		if (Utils.isOnline(context)) {
			Intent iGPS = new Intent(this, net.mobgame.common.GPSService.class);
			startService(iGPS);
			Intent i = new Intent(MainActivity.this, HomeMessage.class);
			startActivity(i);
			MainActivity.this.finish();
		} else Utils.buildAlertMessageNoInterNet(context);
	}

	private final Context context = this;

	// check GPS
	public void checkGPS() {
		boolean enabled = false;

		LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		if(locationNet==null && locationGPS==null)	enabled = false;
		else{
			long GPSLocationTime = 0;
			if (null != locationGPS) GPSLocationTime = locationGPS.getTime();

			long NetLocationTime = 0;

			if (null != locationNet) NetLocationTime = locationNet.getTime();

			if ( 0 < GPSLocationTime - NetLocationTime ) enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
			else enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
		}

		if (!enabled) {
			//			turnOnGPS();
			Utils.buildAlertMessageNoGps(context);
		} else checkGooglePlayServices();
	}

	/**
	 * check Google Play Service
	 */
	public void checkGooglePlayServices() {
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		if(resultCode != ConnectionResult.SUCCESS)	Utils.buildAlertMessageNoGooglePlayService(context);
		else {
			MainActivity.this.finish();
			Intent intent = new Intent(context, HomeMessage.class);
			startActivity(intent);
		}
	}
}
